/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ecom.client;

import ecom.beans.address.*;
import ecom.beans.account.*;
import ecom.beans.cart.*;
import ecom.beans.customer.*;
import ecom.beans.dish.*;
import ecom.beans.customer.*;
import ecom.beans.store.*;
import ecom.beans.menuorder.*;
import ecom.client.*;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import javax.ejb.EJB;

import javax.transaction.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import java.util.Date;
import java.util.GregorianCalendar;


/**
 *
 * @author alina
 */
public class ExternCustomer {
	
	private Context initialContext;
    private UserTransaction utx;
	
    private DishEntityFacadeRemote dishEntityFacade;
    private AccountEntityFacadeRemote accountEntityFacade;
    private CustomerEntityFacadeRemote customerEntityFacade;
    private StoreEntityFacadeRemote storeEntityFacade;
	private AddressEntityFacadeRemote addressEntityFacade;
	private CartSessionRemote cartSessionBean;
	private MenuOrderEntityFacadeRemote menuOrderEntityFacade;

	ExternCustomer() {

        initialContext = null;
        utx = null;
        dishEntityFacade = null;
        accountEntityFacade = null;
        customerEntityFacade = null;
        storeEntityFacade = null;
		addressEntityFacade = null;
		cartSessionBean = null;
		menuOrderEntityFacade = null;

        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.objectweb.carol.jndi.spi.MultiOrbInitialContextFactory");

        try {
            initialContext = new InitialContext();
        } catch (Exception e) {
            System.err.println("Cannot get initial context for JNDI: " + e);
            System.exit(2);
        }

        try {
            utx = (UserTransaction) initialContext.lookup("javax.transaction.UserTransaction");
        } catch (NamingException e) {
            System.err.println("Cannot lookup UserTransaction: " + e);
            System.exit(2);
        }

		
        try {
            dishEntityFacade = (DishEntityFacadeRemote) initialContext.lookup("ecom.beans.dish.DishEntityFacade" + "_" + DishEntityFacadeRemote.class.getName() + "@Remote");

            System.out.println("Creation of dishEntityFacade...OK");

        } catch (NamingException e) {
            System.err.println("Cannot get dishEntityFacade : " + e);
            System.exit(2);
        }


        try {
            storeEntityFacade = (StoreEntityFacadeRemote) initialContext.lookup("ecom.beans.store.StoreEntityFacade" + "_" + StoreEntityFacadeRemote.class.getName() + "@Remote");

            System.out.println("Creation of storeEntityFacade...OK");



        } catch (NamingException e) {
            System.err.println("Cannot get storeEntityFacade : " + e);
            System.exit(2);
        }

        try {
            customerEntityFacade = (CustomerEntityFacadeRemote) initialContext.lookup("ecom.beans.customer.CustomerEntityFacade" + "_" + CustomerEntityFacadeRemote.class.getName() + "@Remote");

            System.out.println("Creation of customerEntityFacade...OK");



        } catch (NamingException e) {
            System.err.println("Cannot get customerEntityFacade : " + e);
            System.exit(2);
        }


        try {
            accountEntityFacade = (AccountEntityFacadeRemote) initialContext.lookup("ecom.beans.account.AccountEntityFacade" + "_" + AccountEntityFacadeRemote.class.getName() + "@Remote");

            System.out.println("Creation of accountEntityFacade...OK");



        } catch (NamingException e) {
            System.err.println("Cannot get accountEntityFacade : " + e);
            System.exit(2);
        }
		
		
		try {
            addressEntityFacade = (AddressEntityFacadeRemote) initialContext.lookup("ecom.beans.address.AddressEntityFacade" + "_" + AddressEntityFacadeRemote.class.getName() + "@Remote");

            System.out.println("Creation of addressEntityFacade...OK");

        } catch (NamingException e) {
            System.err.println("Cannot get addressEntityFacade : " + e);
            System.exit(2);
        }
		
		
		try {
            cartSessionBean = (CartSessionRemote) initialContext.lookup("ecom.beans.cart.CartSessionBean" + "_" + CartSessionRemote.class.getName() + "@Remote");

            System.out.println("Creation of cartSessionBean...OK");

        } catch (NamingException e) {
            System.err.println("Cannot get cartSessionBean : " + e);
            System.exit(2);
        }
		
		try {
            menuOrderEntityFacade = (MenuOrderEntityFacadeRemote) initialContext.lookup("ecom.beans.menuorder.MenuOrderEntityFacade" + "_" + MenuOrderEntityFacadeRemote.class.getName() + "@Remote");

            System.out.println("Creation of menuOrderEntityFacade...OK");

        } catch (NamingException e) {
            System.err.println("Cannot get menuOrderEntityFacade : " + e);
            System.exit(2);
        }
		
    }
	
	
	/************************************************************************************************************************/
	
	public void customer() {
        boolean customerIsLogged = false;
        CustomerEntity loggedCustomer = null;
        while (true) {
            try {


                System.out.println("------------------------------------------------------");
                System.out.println("Entrer une commande :");
                if (customerIsLogged == false) {
                    System.out.println("1 = Creer un nouveau compte client");
                    System.out.println("2 = S'identifier");
                    System.out.println("5 = Voir la liste des plats");
                    System.out.println("0 = Quitter l'application\n");
                } else {

					System.out.println("3 = Voir les informations de votre compte client");
                    System.out.println("4 = Modifier votre compte client");
                    System.out.println("5 = Voir la liste des plats");
                    System.out.println("6 = Gerer votre panier");
                    System.out.println("7 = Se deconnecter");
                    System.out.println("8 = Supprimer votre compte client\n");

                    System.out.println("0 = Quitter l'application\n");
                }
                int choice = Tx.readInt();

                switch (choice) {
                    case 1:
						// dong tian
                        //if (customerIsLogged == false) {
						if (customerIsLogged == true) {
						System.out.println("Valeur incorrecte.");
                        } else {

                            // We get the informations regarding a new customer from the administrator
                            // We verify the informations are correctly typed
                            System.out.println("Entrez les informations vous concernant :");
                            System.out.println("Prenom : ");
                            String firstname = Tx.readString();
                            while (firstname.matches("[a-zA-Zéèçàù-[ ]]+") == false) {
                                System.out.println("Prenom incorrect, recommencez : ");
                                firstname = Tx.readString();
                            }
                            System.out.println("Nom : ");
                            String lastname = Tx.readString();
                            while (lastname.matches("[a-zA-Zéèçàù-[ ]]+") == false) {
                                System.out.println("Nom incorrect, recommencez : ");
                                lastname = Tx.readString();
                            }
                            System.out.println("Numero de telephone (chiffres uniquement) : ");
                            String tel = Tx.readString();
                            while (tel.matches("[0-9]+") == false) {
                                System.out.println("Numero de telephone incorrect, recommencez : ");
                                tel = Tx.readString();
                            }
                            System.out.println("Adresse e-mail : ");
                            String email = Tx.readString();
                            while (email.matches("(\\w+)@(\\w+\\.)(\\w+)(\\.\\w+)*") == false) {
                                System.out.println("Adresse e-mail incorrecte, recommencez : ");
                                email = Tx.readString();
                            }
                            System.out.println("Mot de passe (lettres, chiffres, tirets) : ");
                            String password = Tx.readString();
                            while (password.matches("[a-zA-Z0-9-_]+") == false) {
                                System.out.println("Mot de passe incorrect, recommencez : ");
                                password = Tx.readString();
                            }
                            System.out.println("Entrez les informations concernant l'adresse du client :");
                            AddressEntity address = readAddress(1);
                            System.out.println("adresse creee");

                            System.out.println("Entrez les informations concernant le compte bancaire du client :");
                            AccountEntity account = readAccount(1);
                            System.out.println("compte bancaire cree");




                            CustomerEntity newCustomer = customerEntityFacade.registerCustomer(password, email, firstname, lastname, tel, address, account);


                            if (newCustomer == null) {
                                System.out.println("Le compte client n'a pas ete cree");
                            } else {
                                System.out.println("Compte client cree.");
                            }
                        }

                        break;


                    case 2:
					
					// dong modifiy
					/*******************************************/
					 if (customerIsLogged == false) {
                            loggedCustomer = login();
                            if (loggedCustomer == null) {
                                customerIsLogged = false;
                            } else {
                                customerIsLogged = true;
                                //Initialiser le panier ou le recuperer
                                CartEntity cartExists = cartSessionBean.getCartById(loggedCustomer.getId());
                                if (cartExists!=null) {
                                  
                                } else {
                                    cartSessionBean.initCart(loggedCustomer.getId());
                                }
                            }
                        } else {
                            System.out.println("Il faut auparavant vous deconnecter avant de pouvoir vous identifier.");
                        }
                        break;

					/*******************************************/
					/*
                        if (customerIsLogged == false) {
                            loggedCustomer = login();
                            if (loggedCustomer == null) {
                                customerIsLogged = false;
                            } else {
                                customerIsLogged = true;
                                CartEntity cart = cartSessionBean.getCartById(loggedCustomer.getId());
                                if (cart == null) {
                                    cartSessionBean.initCart(loggedCustomer.getId());
                                    //customerEntityFacade.createCart(loggedCustomer);
                                }
                            }
                        } else {
                            System.out.println("Il faut auparavant vous deconnecter avant de pouvoir vous identifier.");
                        }
                        break;
						*/
                    case 3:
                        if (customerIsLogged == false) {
                            System.out.println("Valeur incorrecte.");
                        } else {
							System.out.println("----------------I-N-F-O----------------\n");
                            System.out.println("Voici les informations du compte:");
							System.out.println("    [Email] : " + loggedCustomer.getEmail());
                            System.out.println("     [Name] : " + loggedCustomer.getFirstname() + " " + loggedCustomer.getLastname());
                            System.out.println("[Telephone] : " + loggedCustomer.getTel());
                            System.out.println(" [Fidelite] : " + loggedCustomer.getSmilesNumber());
                            AddressEntity address = loggedCustomer.getCustomerAddress();
                            System.out.println("  [Adresse] : " + address.getStreetNum() + " rue " + address.getStreetName() + " " + address.getZipcode() + " " + address.getCity());
                            System.out.println("     [IBAN] : " + loggedCustomer.getCustomerAccount().getAccountIBAN());
                            System.out.println("    [Solde] : " + loggedCustomer.getCustomerAccount().getAccountBalance() + " euros");
                        }
                        break;
                    case 4:
                        //   listProductsInCart(customerBean);
                        if (customerIsLogged == false) {
                            System.out.println("Valeur incorrecte.");
                        } else {
                            System.out.println("Quelles informations voulez-vous modifier ? \n(Touche entree pour ne pas modifier la valeur)");
                            System.out.println("Numero de telephone actuel : " + loggedCustomer.getTel());
                            System.out.println("Nouveau numero de telephone (chiffres uniquement) :");
                            String tel = Tx.readString();
                            if (tel.matches("")) {
                            } else {
                                while (tel.matches("[0-9]+") == false) {
                                    System.out.println("Numero de telephone incorrect, recommencez : ");
                                    tel = Tx.readString();
                                }
                                loggedCustomer.setTel(tel);
                            }

                            System.out.println("Nouveau mot de passe (lettres, chiffres, tirets) :");
                            String password = Tx.readString();
                            if (password.matches("")) {
                            } else {
                                while (password.matches("[a-zA-Z0-9-_]+") == false) {
                                    System.out.println("Mot de passe incorrect, recommencez : ");
                                    password = Tx.readString();
                                }
                                loggedCustomer.setPassword(password);
                            }

                            System.out.println("[Nouvelle adresse]\n");
                            AddressEntity newAddress = modifyAddress(loggedCustomer.getCustomerAddress());
                            loggedCustomer.setCustomerAddress(newAddress);

                            customerEntityFacade.updateCustomer(loggedCustomer);
                            System.out.println("Le compte associee a l'adresse e-mail : " + loggedCustomer.getEmail() + " a ete modifie.");

                        }
                        break;
                    case 5:
                        List<DishEntity> dishList = null;
                        dishList = dishEntityFacade.getAllDishes();
                        if (dishList != null && dishList.size() > 0) {

                            System.out.println("-------------------------------");
                            for (DishEntity dish : dishList) {
							
								if(dish.getDishName().length()>35){
								
									System.out.println("[" + dish.getDishId() + "] " + dish.getDishName() + "\t[" + dish.getPrice() + "] Euro");
								}
								else if(dish.getDishName().length()<=15){
									
									System.out.println("[" + dish.getDishId() + "] " + dish.getDishName() + "\t\t\t\t\t[" + dish.getPrice() + "] Euro");
								}
								else if(dish.getDishName().length()<=24 &&  dish.getDishName().length()>16){
									
									System.out.println("[" + dish.getDishId() + "] " + dish.getDishName() + "\t\t\t\t[" + dish.getPrice() + "] Euro");
								}
								else if(dish.getDishName().length()==25){
									
									System.out.println("[" + dish.getDishId() + "] " + dish.getDishName() + "\t\t\t[" + dish.getPrice() + "] Euro");
								}
								else
									System.out.println("[" + dish.getDishId() + "] " + dish.getDishName() + "\t\t\t\t[" + dish.getPrice() + "] Euro");
                                
                            }

                        } else {
                            System.out.println("Aucun plat dans le menu.");
                        }
                        break;


                    case 6:
                        if (customerIsLogged == false) {
                            System.out.println("Valeur incorrecte.");
                        } else {
                            boolean inCartSubMenu = true;
                            while (inCartSubMenu) {
                                System.out.println("------------------------------------------------------");
                                System.out.println("Entrer une commande :");
                                System.out.println("1 = Ajouter des plats a votre panier");
                                System.out.println("2 = Voir le contenu de votre panier");
                                System.out.println("3 = Modifier le contenu de votre panier");
                                System.out.println("4 = Acheter les plats contenus dans votre panier");
                                System.out.println("5 = Vider votre panier");
                                System.out.println("0 = Revenir au menu principal\n");

                                List<ItemEntity> itemList = null;
                                int choiceCart = Tx.readInt();

                                switch (choiceCart) {
                                    case 1:
                                        List<DishEntity> dishListForCustomer = null;
                                        dishListForCustomer = dishEntityFacade.getAllDishesForCustomer();
                                        if (dishListForCustomer != null && dishListForCustomer.size() > 0) {
                                            System.out.println("Voici la liste des plats disponibles:");
                                            System.out.println("-------------------------------");
                                            for (DishEntity dish : dishListForCustomer) {
											
											if(dish.getDishName().length()>35){
								
									System.out.println("[" + dish.getDishId() + "] " + dish.getDishName() + "\t[" + dish.getPrice() + "] Euro");
								}
								else if(dish.getDishName().length()<=15){
									
									System.out.println("[" + dish.getDishId() + "] " + dish.getDishName() + "\t\t\t\t\t[" + dish.getPrice() + "] Euro");
								}
								else if(dish.getDishName().length()<=24 &&  dish.getDishName().length()>16){
									
									System.out.println("[" + dish.getDishId() + "] " + dish.getDishName() + "\t\t\t\t[" + dish.getPrice() + "] Euro");
								}
								else if(dish.getDishName().length()==25){
									
									System.out.println("[" + dish.getDishId() + "] " + dish.getDishName() + "\t\t\t[" + dish.getPrice() + "] Euro");
								}
								else
									System.out.println("[" + dish.getDishId() + "] " + dish.getDishName() + "\t\t\t\t[" + dish.getPrice() + "] Euro");
											
											
											
                                                //System.out.println("[" + dish.getDishId() + "] " + dish.getDishName() + " " + dish.getPrice() + " euro; quantite dans le stock " + dish.getQuantity());
                                            }
                                            System.out.println("-------------------------------");
                                            System.out.println("Choisissez un plat par son identifiant:");
                                            int choiceIdDish = Tx.readInt();

                                            DishEntity temp = null;

                                            while (temp == null) {
                                                temp = dishEntityFacade.getDishById(choiceIdDish);
                                                if (temp == null) {
                                                    System.out.println("Aucun plat avec cet id. Recommencez:\n");
                                                    choiceIdDish = Tx.readInt();
                                                }

                                            }
                                            System.out.println("Entrez la quantite souhaitee:\n");
                                            int quantity = Tx.readInt();
                                            while ((quantity > temp.getQuantity()) || (quantity < 1)) {
                                                System.out.println("Quantite dans les stock insuffisante! Recommencez:\n");
                                                quantity = 0;
                                                quantity = Tx.readInt();

                                            }
                                            cartSessionBean.addProduct(loggedCustomer.getId(), choiceIdDish, quantity);
                                            System.out.println("Le plat " + temp.getDishName() + " a ete ajoute au panier.\n");
                                        }
                                        break;
                                    case 2:
                                        itemList = cartSessionBean.getAllCartItems(loggedCustomer.getId());

                                        if (itemList != null) {

                                            System.out.println("----------------------");
                                            System.out.println("Voici la liste des plats de votre panier :");
                                            System.out.println("Nom----Type----Prix----QT------------------\n");
                                            for (ItemEntity item : itemList) {
                                                System.out.println(item.getItemProduct().getDishName() + "    " + item.getItemProduct().getDishType() + "    " + item.getItemProduct().getPrice() + "    " + item.getItemQuantity());
                                            }

                                            System.out.println("\nPrix de l'ensemble de votre panier : " + cartSessionBean.getTotalPrice(loggedCustomer.getId()));

                                        } else {

                                            System.out.println("Vous n'avez aucun article dans votre panier.");

                                        }
                                        break;
                                    case 3:
                                        itemList = cartSessionBean.getAllCartItems(loggedCustomer.getId());
                                        if (itemList != null) {
                                            boolean choiceSubmenuMade = false;

                                            while (choiceSubmenuMade == false) {
                                                System.out.println("1 = Modifier la quantite d'un plat");
                                                System.out.println("2 = Supprimer un plat");
                                                System.out.println("0 = Quitter");
                                                int choiceSubmenu = Tx.readInt();
                                                switch (choiceSubmenu) {
                                                    case 1:
                                                        itemList = cartSessionBean.getAllCartItems(loggedCustomer.getId());
                                                        if ((itemList != null) && (itemList.size() != 0)) {
                                                            System.out.println("----------------------");
                                                            System.out.println("Voici la liste des plats de votre panier :");
                                                            System.out.println("Id----Nom----Type----Prix----QT------------------");
                                                            itemList = cartSessionBean.getAllCartItems(loggedCustomer.getId());
                                                            for (ItemEntity item : itemList) {
                                                                System.out.println(item.getItemProduct().getDishId() + " " + item.getItemProduct().getDishName() + "    " + item.getItemProduct().getDishType() + "    " + item.getItemProduct().getPrice() + "    " + item.getItemQuantity());
                                                            }

                                                            System.out.println("Choisissez un plat par son identifiant:");
                                                            int choiceIdItem = Tx.readInt();

                                                            ItemEntity temp = null;
                                                            while (temp == null) {
                                                                for (ItemEntity item : itemList) {
                                                                    if (item.getItemProduct().getDishId() == choiceIdItem) {
                                                                        temp = item;
                                                                        break;
                                                                    }
                                                                }
                                                                if (temp == null) {
                                                                    System.out.println("Le plat ne se trouve pas dans votre panier. Recommencez.");
                                                                    choiceIdItem = Tx.readInt();
                                                                }
                                                            }

                                                            System.out.println("Entrez la nouvelle quantite souhaitee");
                                                            int quantity = Tx.readInt();
                                                            while ((quantity > temp.getItemProduct().getQuantity()) || (quantity < 1)) {
                                                                System.out.println("Quantite dans les stock insuffisante! Recommencez.");
                                                                quantity = 0;
                                                                quantity = Tx.readInt();

                                                            }
                                                            temp.setItemQuantity(quantity);
                                                            cartSessionBean.updateProduct(temp);
                                                            System.out.println("Quantite modifiee.");
                                                            loggedCustomer = customerEntityFacade.findCustomerById(loggedCustomer.getId());

                                                        //choiceSubmenuMade = true;
                                                        } else {
                                                            System.out.println("Aucun plat dans le panier.");
                                                        }
                                                        break;
                                                    case 2:
                                                        itemList = cartSessionBean.getAllCartItems(loggedCustomer.getId());
                                                        if ((itemList != null) && (itemList.size() != 0)) {
                                                            System.out.println("----------------------");
                                                            System.out.println("Voici la liste des plats de votre panier :");
                                                            System.out.println("Id----Nom----Type----Prix----QT------------------");

                                                            for (ItemEntity item : itemList) {
                                                                System.out.println(item.getItemProduct().getDishId() + " " + item.getItemProduct().getDishName() + "    " + item.getItemProduct().getDishType() + "    " + item.getItemProduct().getPrice() + "    " + item.getItemQuantity());
                                                            }
                                                            System.out.println("Choisissez un plat par son identifiant:");
                                                            int choiceIdItemForRemove = Tx.readInt();

                                                            ItemEntity tempRemove = null;
                                                            while (tempRemove == null) {
                                                                for (ItemEntity item : itemList) {
                                                                    if (item.getItemProduct().getDishId() == choiceIdItemForRemove) {
                                                                        tempRemove = item;
                                                                        break;
                                                                    }
                                                                }
                                                                if (tempRemove == null) {
                                                                    System.out.println("Le plat ne se trouve pas dans votre panier. Recommencez.");
                                                                    choiceIdItemForRemove = Tx.readInt();
                                                                }
                                                            }
                                                            cartSessionBean.removeProduct(loggedCustomer.getId(), choiceIdItemForRemove);
                                                            System.out.println("Le plat a ete supprime");
                                                            loggedCustomer = customerEntityFacade.findCustomerById(loggedCustomer.getId());
                                                        } else {
                                                            System.out.println("Aucun plat a supprimer.");
                                                        }
                                                        break;

                                                    case 0:
                                                        choiceSubmenuMade = true;
                                                        break;
                                                    default:
                                                        System.out.println("Valeur incorrecte.");

                                                }


                                            }
                                        } else {

                                            System.out.println("Vos n'avez aucun article dans votre panier.");

                                        }
                                        break;
                                    case 4:
                                        double accountBalance = loggedCustomer.getCustomerAccount().getAccountBalance();
                                        double totalPrice = cartSessionBean.getTotalPrice(loggedCustomer.getId());
                                        System.out.println("Solde de votre compte bancaire : " + accountBalance + " euros.");
                                        System.out.println("Prix de l'ensemble de votre panier : " + totalPrice);
                                        if ((totalPrice <= accountBalance) && (totalPrice > 0)) {
                                            System.out.println("Etes vous sur de vouloir valider votre paiement ?");
                                            boolean choice_made = false;
                                            while (!choice_made) {
                                                System.out.println("1 = OUI ");
                                                System.out.println("2 = NON ");
                                                int yesOrNo = Tx.readInt();
                                                if (yesOrNo == 1) {
                                                    loggedCustomer.setCustomerAccount(cartSessionBean.validPayment(loggedCustomer.getId(), loggedCustomer.getCustomerAccount().getAccountIBAN()));
                                                    System.out.println("Paiement effectue.");
                                                    accountBalance = loggedCustomer.getCustomerAccount().getAccountBalance();
                                                    System.out.println("Nouveau solde: " + accountBalance + " euros.");
                                                    Date desiredDeliveryDate = new GregorianCalendar(2008, 11, 31, 23, 59).getTime();
                                                    registerOrder(loggedCustomer, desiredDeliveryDate, totalPrice);

                                                    choice_made = true;
                                                } else if (yesOrNo == 2) {
                                                    choice_made = true;
                                                } else {
                                                    System.out.println("Mauvais choix, recommencez.");
                                                }

                                            }

                                        } else if (totalPrice > accountBalance) {
                                            System.out.println("Solde de votre compte insuffisant.");
                                        } else {
                                            System.out.println("Rien a acheter.");
                                        }
                                        break;
                                    case 5:
                                        boolean a = cartSessionBean.removeAllItemsByCartId(loggedCustomer.getId());
                                        System.out.println("Votre panier est desormais vide.");
                                        break;
                                    case 0:
                                        inCartSubMenu = false;
                                        break;
                                    default:
                                        System.out.println("Valeur incorrecte.");
                                }
                            }
                        }

                    case 7:
                        if (customerIsLogged == false) {
                            System.out.println("Valeur incorrecte.");
                        } else {
                            customerIsLogged = false;
                            System.out.println("Vous avez ete correctement deconnecte");
                        }
                        break;
                    case 8:
                        if (customerIsLogged == false) {
                            System.out.println("Valeur incorrecte.");
                        } else {
                            System.out.println("Etes vous sur de vouloir supprimer : \nle compte associe a l'e-mail " + loggedCustomer.getEmail());
                            System.out.println("Cette action sera irreversible.");
                            boolean choice_made = false;
                            while (!choice_made) {
                                System.out.println("1 = OUI ");
                                System.out.println("2 = NON ");
                                int yesOrNo = Tx.readInt();
                                if (yesOrNo == 1) {
                                    cartSessionBean.removeAllItemsByCartId(loggedCustomer.getId());
                                    List<CustomerEntity> customerList = customerEntityFacade.removeCustomer(loggedCustomer.getEmail(), loggedCustomer.getPassword());
									
									/****/
									cartSessionBean.removeAllItemsByCartId(loggedCustomer.getId());
									cartSessionBean.removeCartById(loggedCustomer.getId());

									/***/
                                    System.out.println("Le compte client a ete supprime.");
                                    choice_made = true;
                                    customerIsLogged = false;
                                } else if (yesOrNo == 2) {
                                    choice_made = true;
                                } else {
                                    System.out.println("Mauvais choix, recommencez.");
                                }
                            }
                            break;
                        }

                    case 0:
                        System.exit(0);
                        break;
                    default:
                        System.out.println("Valeur incorrecte.");
                }
            } catch (Exception e) {
                e.printStackTrace(System.err);
            }
        }
    }

    private AddressEntity readAddress(int addressType) { //addressType = 1 for a customer, 2 for a restaurant

        AddressEntity address = new AddressEntity();

        address.setAddressType(addressType);

        System.out.println("Numero de la rue : ");
        String streetNum = Tx.readString();
        while (streetNum.matches("[0-9]+") == false) {
            System.out.println("Numero incorrect, recommencez : ");
            streetNum =
                    Tx.readString();
        }

        address.setStreetNum(Integer.parseInt(streetNum));
        System.out.println("Nom de la rue : ");
        String streetName = Tx.readString();
        while (streetName.matches("[a-zA-Zéèçàù-[ ]]+") == false) {
            System.out.println("Nom de rue incorrect, recommencez : ");
            streetName =
                    Tx.readString();
        }

        address.setStreetName(streetName);
        System.out.println("Code postal : ");
        String zipcode = Tx.readString();
        while (zipcode.matches("[0-9]+") == false) {
            System.out.println("Code postal incorrect, recommencez : ");
            zipcode = Tx.readString();
        }

        address.setZipcode(zipcode);
        System.out.println("Ville : ");
        String city = Tx.readString();
        while (city.matches("[a-zA-Zéèçàù-[ ]]+") == false) {
            System.out.println("Nom de ville incorrect, recommencez : ");
            city =
                    Tx.readString();
        }

        address.setCity(city);

        // If we are reading the address of a customer, we have to ask if he/she leaves 
        // in a house or an apartment
        if (addressType == 1) {
            System.out.println("Le client habite-t'il dans un appartement ou une maison ?");

            boolean choice_made = false;

            while (!choice_made) {
                System.out.println("1 = appartement ");
                System.out.println("2 = maison ");
                int choice = Tx.readInt();
                if (choice == 1) {
                    System.out.println("Numero du batiment : ");
                    String buildingNum = Tx.readString();
                    while (buildingNum.matches("[0-9]+") == false) {
                        System.out.println("Numero incorrect, recommencez : ");
                        buildingNum =
                                Tx.readString();
                    }

                    address.setBuildingNum(Integer.parseInt(buildingNum));
                    System.out.println("Numero de l'etage : ");
                    String floorNum = Tx.readString();
                    while (floorNum.matches("[0-9]+") == false) {
                        System.out.println("Numero incorrect, recommencez : ");
                        floorNum =
                                Tx.readString();
                    }

                    address.setFloorNum(Integer.parseInt(floorNum));
                    System.out.println("Numero de l'appartement : ");
                    String apartmentNum = Tx.readString();
                    while (apartmentNum.matches("[0-9]+") == false) {
                        System.out.println("Numero incorrect, recommencez : ");
                        apartmentNum =
                                Tx.readString();
                    }

                    address.setApartmentNum(Integer.parseInt(apartmentNum));
                    choice_made =
                            true;
                } else if (choice == 2) {
                    address.setBuildingNum(-1);
                    address.setFloorNum(-1);
                    address.setApartmentNum(-1);
                    choice_made =
                            true;
                } else {
                    System.out.println("Mauvais choix, recommencez.");
                }

            }
        }
        return address;
    }

    private AddressEntity modifyAddress(AddressEntity address) { //addressType = 1 for a customer, 2 for a restaurant

        AddressEntity newAddress = new AddressEntity();
        newAddress.setId(address.getId());

        newAddress.setAddressType(address.getAddressType());

        System.out.println("Numero de la rue actuel : " + address.getStreetNum());
        System.out.println("Nouveau numero de rue : ");
        String streetNum = Tx.readString();
        if (streetNum.matches("")) {
            newAddress.setStreetNum(address.getStreetNum());
        } else {
            while (streetNum.matches("[0-9]+") == false) {
                System.out.println("Numero incorrect, recommencez : ");
                streetNum =
                        Tx.readString();
            }

            newAddress.setStreetNum(Integer.parseInt(streetNum));
        }

        System.out.println("Nom de la rue actuel : " + address.getStreetName());
        System.out.println("Nouveau nom de rue : ");
        String streetName = Tx.readString();
        if (streetName.matches("")) {
            newAddress.setStreetName(address.getStreetName());
        } else {
            while (streetName.matches("[a-zA-Zéèçàù-[ ]]+") == false) {
                System.out.println("Nom de rue incorrect, recommencez : ");
                streetName =
                        Tx.readString();
            }

            newAddress.setStreetName(streetName);
        }

        System.out.println("Code postal actuel  " + address.getZipcode());
        System.out.println("Nouveau code postal : ");
        String zipcode = Tx.readString();
        if (zipcode.matches("")) {
            newAddress.setZipcode(address.getZipcode());
        } else {
            while (zipcode.matches("[0-9]+") == false) {
                System.out.println("Code postal incorrect, recommencez : ");
                zipcode =
                        Tx.readString();

            }

            newAddress.setZipcode(zipcode);
        }

        System.out.println("Ville actuelle : " + address.getCity());
        System.out.println("Nouvelle ville : ");
        String city = Tx.readString();
        if (city.matches("")) {
            newAddress.setCity(address.getCity());
        } else {
            while (city.matches("[a-zA-Zéèçàù-[ ]]+") == false) {
                System.out.println("Nom de ville incorrect, recommencez : ");
                city =
                        Tx.readString();
            }

            newAddress.setCity(city);
        }

// If we are reading the address of a customer, we have to ask if he/she leaves 
// in a house or an apartment
        if (newAddress.getAddressType() == 1) {
            System.out.println("Habitez-vous dans un appartement ou une maison ?");

            boolean choice_made = false;

            while (!choice_made) {
                System.out.println("1 = appartement ");
                System.out.println("2 = maison ");
                int choice = Tx.readInt();
                if (choice == 1) {
                    if (address.getBuildingNum() != -1) {
                        System.out.println("Numero du batiment actuel : " + address.getBuildingNum());
                    }

                    System.out.println("Nouveau numero de batiment : ");
                    String buildingNum = Tx.readString();
                    if (buildingNum.matches("")) {
                        newAddress.setBuildingNum(address.getBuildingNum());
                    } else {
                        while (buildingNum.matches("[0-9]+") == false) {
                            System.out.println("Numero incorrect, recommencez : ");
                            buildingNum =
                                    Tx.readString();
                        }

                        newAddress.setBuildingNum(Integer.parseInt(buildingNum));
                    }

                    if (address.getFloorNum() != -1) {
                        System.out.println("Numero de l'etage actuel : " + address.getFloorNum());
                    }

                    System.out.println("Nouveau numero d'etage : ");
                    String floorNum = Tx.readString();
                    if (floorNum.matches("")) {
                        newAddress.setFloorNum(address.getFloorNum());
                    } else {
                        while (floorNum.matches("[0-9]+") == false) {
                            System.out.println("Numero incorrect, recommencez : ");
                            floorNum =
                                    Tx.readString();
                        }

                        address.setFloorNum(Integer.parseInt(floorNum));
                    }

                    if (address.getApartmentNum() != -1) {
                        System.out.println("Numero de l'appartement actuel : " + address.getApartmentNum());
                    }

                    System.out.println("Nouveau numero d'appartement : ");
                    String apartmentNum = Tx.readString();
                    if (apartmentNum.matches("")) {
                        newAddress.setApartmentNum(address.getApartmentNum());
                    } else {
                        while (apartmentNum.matches("[0-9]+") == false) {
                            System.out.println("Numero incorrect, recommencez : ");
                            apartmentNum =
                                    Tx.readString();
                        }

                        newAddress.setApartmentNum(Integer.parseInt(apartmentNum));
                    }

                    choice_made = true;
                } else if (choice == 2) {
                    choice_made = true;
                } else {
                    System.out.println("Mauvais choix, recommencez.");
                }

            }
        }

        return newAddress;
    }

    private AccountEntity readAccount(int accountType) {  //accountType = 1 for a customer, 2 for a restaurant

        AccountEntity account;

        System.out.println("IBAN du compte (FRxxx...) : ");
        String iban = Tx.readString();
        while (iban.matches("FR[0-9]+") == false) {
            System.out.println("IBAN incorrect, recommencez : ");
            iban =
                    Tx.readString();
        }

        account = accountEntityFacade.getAccountByAccountIBAN(iban);
        while (account != null) {
            System.out.println("Le compte bancaire \"" + account.getAccountIBAN() + "\" existe deja.");
            System.out.println("IBAN du compte (FRxxx...) : ");
            iban =
                    Tx.readString();
            while (iban.matches("FR[0-9]+") == false) {
                System.out.println("IBAN incorrect, recommencez : ");
                iban =
                        Tx.readString();
            }

            account = accountEntityFacade.getAccountByAccountIBAN(iban);
        }

        account = new AccountEntity();
        account.setAccountType(accountType);
        account.setAccountIBAN(iban);
        return account;
    }

   
    private void registerOrder(CustomerEntity loggedCustomer, Date desiredDeliveryDate, double orderTotalPrice) {
       
        int type = 1;
 
        System.out.println("Prix: " + orderTotalPrice);
        String customerName = loggedCustomer.getFirstname() + " " + loggedCustomer.getLastname();
  
        String deliveryAddress = loggedCustomer.getCustomerAddress().toString();
        System.out.println("Adresse de livraison " + deliveryAddress);
        Date orderDate = new Date();
        int orderTotalSmiles = calculateSmilesForPrice(orderTotalPrice);
        menuOrderEntityFacade.registerOrder(type, orderTotalPrice, customerName, deliveryAddress, orderDate, desiredDeliveryDate, orderTotalSmiles);
 

    }

	//TODO calculate smiles as a function of the price of the order
    private int calculateSmilesForPrice(double orderPrice) {
        return 10;
    }

    private CustomerEntity login() {
        System.out.println("Entrez votre adresse e-mail : ");
        String email = Tx.readString();
        while (email.matches("(\\w+)@(\\w+\\.)(\\w+)(\\.\\w+)*") == false) {
            System.out.println("Adresse e-mail incorrecte, recommencez : ");
            email =
                    Tx.readString();
        }

        System.out.println("Entrez votre mot de passe : ");
        String password = Tx.readString();
        while (password.matches("[a-zA-Z0-9-_]+") == false) {
            System.out.println("Format de mot de passe incorrect, recommencez : ");
            password =
                    Tx.readString();
        }

        if (customerEntityFacade.findCustomerEmail(email) == true) {
            
            CustomerEntity loggedCustomer = customerEntityFacade.loginCustomer(email, password);
            if (loggedCustomer == null) {
                System.out.println("Le mot de passe est incorrect.");
            } else {
                System.out.println("Vous etes maintenant connecte en tant que " + loggedCustomer.getFirstname() + " " + loggedCustomer.getLastname());

            }
            return loggedCustomer;
        } else {
            System.out.println("L'email entre ne correspond a aucun compte client.");
            return null;
        }

    }

//////////////////////ALINA//////////////////////////////////////
    public void cartGestion(CustomerEntity customer) throws IOException {


        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        List<DishEntity> dishList = null;
        dishList = dishEntityFacade.getAllDishesForCustomer();

        if (dishList != null && dishList.size() > 0) {

            System.out.println("-------------------------------");
            for (DishEntity dish : dishList) {
                System.out.println("[" + dish.getDishId() + "] " + dish.getDishName() + " " + dish.getPrice() + " euro");
            }

            System.out.println("-------------------------------");

            if (cartSessionBean.getCartById(customer.getId()) != null) {

                System.out.println("cart already exists");
                getAllCartItems(customer);


            } else {

                int id = cartSessionBean.initCart(customer.getId());
                System.out.println("Creation a new Cart[" + id + "]");

            }

            /*********************************************************/
            int number;

            while (true) {

                number = 0;
                System.out.println("--------------------------");
                System.out.println("1 - get all cart items");
                System.out.println("2 - add a item");
                System.out.println("3 - remove a item");
                System.out.println("4 - pay all items");
                System.out.println("5 - quit\n");

                number =
                        Integer.parseInt(br.readLine());

                if (number == 1) {

                    getAllCartItems(customer);
                } else if (number == 2) {

                    addItem(customer);

                } else if (number == 3) {


                    removeItem(customer);
                } else if (number == 4) {

                    itemPayment(customer);
                } else if (number == 5) {

                    break;
                } else {

                    System.out.println("wrong number - please try again !");
                }

            }

        } else {

            System.out.println("Sorry no product available now :(");

        }

    }

    private void getAllCartItems(CustomerEntity customer) {


        List<ItemEntity> itemList = null;
        itemList = cartSessionBean.getAllCartItems(customer.getId());

        if (itemList != null) {

            System.out.println("----------------------");
            System.out.println("[your cart items]:");
            for (ItemEntity item : itemList) {

                System.out.println("[PRODUCT] " + item.getItemProduct().getDishName() + " [QUANTITY] " + item.getItemQuantity());

            }

            System.out.println("Total Price : " + cartSessionBean.getTotalPrice(customer.getId()));

        } else {

            System.out.println("your cart is empty now");

        }

    }

    public void addItem(CustomerEntity customer) throws IOException {


        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        int productId = 0;
        int quantity = 0;

        System.out.println("[Product ID]:");
        productId =
                Integer.parseInt(br.readLine());
        System.out.println("[Product QT]:");
        quantity =
                Integer.parseInt(br.readLine());
        cartSessionBean.addProduct(customer.getId(), productId, quantity);

    }

    public void removeItem(CustomerEntity customer) throws IOException {

        int productId = 0;
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);

        System.out.println("[REMOVE ITEM]");
        productId =
                Integer.parseInt(br.readLine());
        cartSessionBean.removeProduct(customer.getId(), productId);

    }

    public void itemPayment(CustomerEntity customer) {

        cartSessionBean.validPayment(customer.getId(), customer.getCustomerAccount().getAccountIBAN());

    }

	
	
	
	
	/************************************************************************************************************************/
	
	public static void main(String[] args) throws Exception {
   
			ExternCustomer customerTest = new ExternCustomer();
			customerTest.customer();
			
    }
	
	
}


